import {REQUEST_AUTH_IDENT} from "@/config/common-config"
import {getOneUserInfoUtil} from "@/utils/common-request.ts";

export const localUserInfoIdent: string = "localUserInfo";
export const localMenuDataIdent: string = "localMenuData";

/**
 * 缓存用户token
 */
export const setToken = (token: string) => {
    localStorage.setItem(REQUEST_AUTH_IDENT, token);
}

/**
 * 缓存用户token
 */
export const getToken = (): string => {
    return localStorage.getItem(REQUEST_AUTH_IDENT) || '';
}

/**
 * 清空用户token
 */
export const clearToken = () => {
    localStorage.removeItem(REQUEST_AUTH_IDENT);
}

/**
 * 本地存储用户所有信息
 */
export const setAllUserInfo = (userInfoParam: any) => {
    setUserInfo(userInfoParam);
    setToken(userInfoParam.token);
    setUserMenu(userInfoParam);
}

/**
 * 本地存储用户信息
 * @param userInfoParam 参数
 */
export const setUserInfo = (userInfoParam: any) => {
    const userInfo: any = {
        userId: userInfoParam.id,
        username: userInfoParam.username,
        userAvatar: userInfoParam.avatarUrl,
        sex: userInfoParam.sex,
        phone: userInfoParam.phone,
        email: userInfoParam.email,
        province: userInfoParam.province,
        city: userInfoParam.city,
        area: userInfoParam.area,
        address: userInfoParam.address,
        description: userInfoParam.description
    }
    localStorage.setItem(localUserInfoIdent, JSON.stringify(userInfo));

}
/**
 * 本地存储用户菜单信息
 * @param userInfoParam 参数
 */
export const setUserMenu = (userInfoParam: any) => {
    const menuData = userInfoParam.menuData;
    localStorage.setItem(localMenuDataIdent, JSON.stringify(menuData));
}

/**
 * 清除用户菜单信息
 */
export const clearUserMenu = () => {
    localStorage.removeItem(localMenuDataIdent);
}

/**
 * 清除用户数据
 */
export const clearAllUserInfo = () => {
    clearToken()
    clearUserInfo()
    clearUserMenu()
}

/**
 * 获取本地存储用户信息
 */
export const getUserInfo = (): any => {
    let userInfoStr: string | null = localStorage.getItem(localUserInfoIdent);
    return JSON.parse(userInfoStr || '');
}

/**
 * 清除本地用户信息
 */
export const clearUserInfo = () => {
    localStorage.removeItem(localUserInfoIdent);
    localStorage.removeItem(localMenuDataIdent);
}

/**
 * 获取本地存储用户信息
 */
export const getUserName = (): string => {
    const userInfo: any = getUserInfo();
    return userInfo.username;
}

/**
 * 获取菜单信息
 */
export const getUserMenu = (): any => {
    let menuData = JSON.parse(localStorage.getItem(localMenuDataIdent) || '');

    menuData.unshift({
        title: '个人中心', path: '/myself', id: "2"
    })

    menuData.unshift({
        title: '首页', path: '/welcome', id: "1"
    })
    return menuData;
}

/**
 * 获取用户头像信息
 */
export const getUserAvatar = (): string => {
    const userInfo = getUserInfo();
    return userInfo.userAvatar;
}

/**
 * 更新用户信息
 * @param userId 用户id
 */
export const updateLocalUserInfo = async (userId: string) => {
    const res: any = await getOneUserInfoUtil(userId)
    setUserInfo(res);
}